package com.qifei.xmlg_backend.service.impl;

import com.qifei.xmlg_backend.entity.User;
import com.qifei.xmlg_backend.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.*;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Slf4j
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectByUsername(username);  // 你需要实现这个方法
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 构造带角色的用户对象，注意角色必须是以 "ROLE_" 开头
        String role = "ROLE_" + user.getRole().replace("role_", "");
        log.info("当前用户权限" + role);
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                Collections.singletonList(new SimpleGrantedAuthority(role))
        );
    }
}